/* eslint-disable no-undef */
import React, { Component } from 'react';
import request from './helper.js'
import './style.css';
import { Redirect } from "react-router-dom";

var viewstate = '';
var viewtor = '';
var viewtion = '';
var isFirst = true;

export default class Login extends Component {

    constructor(props) {
        super(props)
        this.state = {
            username: '',
            password: '',
            myhtml: '',
            login: false
        }
        this.handleClick = this.handleClick.bind(this);
    }


    render() {
        var divStyle = {
            width: 200,
            height: 200,
            left: 207.7,
            top: 90.86,
            display: 'none'
        }

        if (this.state.login) {
            return <Redirect to="/order" />
        }
        return (
            <div className="container">
                账号 <input type='text' ref='input' defaultValue="685124MES" /><br />
                密码 <input type='password' ref='inputpwd' defaultValue="" /><br />
                <button onClick={this.handleSubmit}>登录</button>

                <div style={divStyle} className="html-wrap" dangerouslySetInnerHTML={{ __html: this.state.myhtml }}></div>

            </div>
        )
    }


    componentDidUpdate() {
        if (!isFirst && isEmpty(viewstate)) {
            viewstate = document.getElementById('__VIEWSTATE').value;
            viewtor = document.getElementById('__VIEWSTATEGENERATOR').value;
            viewtion = document.getElementById('__EVENTVALIDATION').value;
            console.log("重新渲染=" + viewtion);
        }

    }

    componentDidMount() {
        if (isFirst) {
            this.handleSubmit();
        }
    }

    handleClick(event) {
        this.setState({ myhtml: event });
    }

    handleSubmit = () => {
        // const url = "/api/GreeMesExtension/Report/ENAllowDeliveryQuantitySearch.aspx?CurrentUserID=204270&MINFO=238s241s20s36s239s51s218s233s21s168s36s205s48s113s121s60s";
        const url = "/api/Gree/Login.aspx";
        const account = this.refs.input.value;
        const psw = this.refs.inputpwd.value;
        let searchParams = new URLSearchParams()
        const mthis = this;

        if (!isFirst && !isEmpty(viewstate)) {
            searchParams.set('__VIEWSTATE', viewstate);
            searchParams.set('__VIEWSTATEGENERATOR', viewtor);
            searchParams.set('__EVENTVALIDATION', viewtion);
            searchParams.set('UserNameText', account);
            searchParams.set('PasswordText', psw);
            searchParams.set('LanguageList', "2052");
            searchParams.set('LoginButton.x', "24");
            searchParams.set('LoginButton.y', "10");
        }

        fetch(url, {
            method: 'POST',
            mode: 'cors',
            credentials: "include",
            headers: {
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
                'Cache-Control': 'no-cache'
                // 'Content-Type': 'application/x-www-form-urlencoded'  不能加这个否则会被转为WebKitFormBoundary格式数据
            },
            body: searchParams
        }).then(function (response) {
            // console.log(response.headers);
            if (response.status === 200) {
                if (isEmpty(viewstate)) {
                    console.log("viewstate为空");
                    return response.text();
                } else if (response.url.indexOf("Default.aspx") != -1) {// 包含   
                    mthis.state.login = true;
                    return response.text();
                }
            }
            alert("登录失败");
            const error = new Error(response.statusText)
            error.response = response
            throw error
        })
            .then(function (data) {
                isFirst = false;
                mthis.handleClick(data);
                // console.log(data);
            })
            .catch(error => console.log('error is', error));

    }

}


function isEmpty(obj) {
    if (typeof obj == "undefined" || obj == null || obj == "") {
        return true;
    } else {
        return false;
    }
}



